#include "relay.h"
#include "key.h"
#include "device.h"
/********************************************************/
GPIO relay_port[RELAYNUM] = {PA7 , PB0 , PB1 , PB2 , PB10 , PB11 , PA0 , PA1 , PA2 , PA3 , PA4 , PA5 , PA6};
static uint32_t on_time[RELAYNUM] = {0};
static uint32_t off_time[RELAYNUM] = {0}; 
/********************************************************/

/********************************************************/
void relay_init()
{
	for (int i = 0; i < 13; i++)
	{
		relay_port[i].mode(OUTPUT_PP);
		on_time[i] = 0;
		off_time[i] = 0;
	}
}
void relay_write(uint8_t index,bool val)
{
	relay_port[index].write(val);
}
uint8_t relay_read(uint8_t index)
{
	return relay_port[index].read();
}
void relay_on(uint8_t index)
{
	//relay_port[index].set();
	device.physical_control(index , 1);
}
void relay_off(uint8_t index)
{
	//relay_port[index].reset();
	device.physical_control(index , 0);
}
void relay_toggle(uint8_t index)
{
	device.physical_control(index ,!relay_read(index));
}
void relay_delay_on(uint8_t index,uint16_t time)
{
	on_time[index] = time + 1;
}
void relay_delay_off(uint8_t index,uint16_t time)
{
	off_time[index] = time + 1;
}
//开，延时关
void relay_turnoff_delay(uint8_t index,uint16_t offtime)
{
	relay_on(index);
	relay_delay_off(index , offtime);
}
void relay_task()
{
	for (int i = 0; i < RELAYNUM; i++)
	{
		if(on_time[i])
		{
			on_time[i]--;
			if(1 == on_time[i])
				//relay_port[i].set();
					relay_on(i);
		}
		if(off_time[i])
		{
			off_time[i]--;
			if(1 == off_time[i])
				//relay_port[i].reset();
					relay_off(i);
		}
	}
}



